<template>
	<view class="container">
		<uni-forms ref="customForm" :modelValue="formData" @change="onFormChange">
    <!--   评价项打分   -->
      <template v-for="(itemType, typeIndex) in questionList" >
        <uni-section  :title="itemType.itemTypeName" :key="itemType.itemTypeId">
          <view class="example">
            <template v-for="(item, itemIndex) in itemType.itemList">
              <uni-forms-item  :key="item.itemId" :label="item.itemContent" required>
                <uni-data-checkbox :localdata="item.optionList"
                                   v-model="formData[item.itemId]"
                                   @change="onCheckboxChange(itemType,item)"/>
              </uni-forms-item>
            </template>
          </view>
        </uni-section>
      </template>
      <!--   整体评价   -->
      <uni-section  title="总体评价">
        <view class="example">
          <uni-forms-item label="评价总分"  required >
            <uni-easyinput v-model="postData.score" :disabled="true"/>
          </uni-forms-item>
          <uni-forms-item label="评价等级(建议评价总分大于90分可选择A类等级；小于90分且大于80分可选择B类等级；小于80分可选择C类等级。)"  required>
            <uni-data-checkbox v-model="postData.scoreLevel"  :localdata="scoreLevel"/>
          </uni-forms-item>
        </view>
      </uni-section>

		<view class="example btn_submit">
			<button type="primary" @click="goProStage()">{{$t('common.nextStep')}}</button>
		</view>
		</uni-forms>
	</view>
</template>
<script>
import { isLogin } from '@/../utils/auth';
import { questionList } from '@/../utils/questionList';
import {insertScore} from "@/api/eval";
import { scoreLevel } from '@/../utils/enums';
import Decimal from "decimal.js";
export default {
	onShow() {
	},
	onLoad: function () {
    console.log("onload")
		isLogin(this);
	},
  onBackPress() {
    // 在这里编写自定义的返回逻辑
    console.log('自定义返回逻辑触发');
    // 可以在这里执行一些其他操作，比如提示用户确认返回
    uni.showModal({
      title: '提示',
      content: '评价未完成，返回将重新进行评价，确定要返回吗？',
      confirmColor:"#e8380d",
      success: (res) => {
        if (res.confirm) {
          // 用户点击确定，执行默认返回操作
          uni.redirectTo({
            url: `/pages/eval/index`
          })
        }
      }
    });
    // 返回 true 表示阻止默认返回行为，返回 false 表示允许默认返回行为
    return true;
  },
  created() {
    // 从传参中获取recordId
    this.postData.recordId = this.$route.query.recordId;
    if(this.postData.recordId === null || this.postData.recordId === undefined){
      uni.showToast({
        title: '请先选择课程',
        icon: 'error',
        duration: 2000,
        complete: function () {
          // 跳转选择课程页面
          uni.redirectTo({
            url: `/pages/eval/index`,
          })
        }
      });
    }
    console.log( this.postData);
    // 初始化 formData，确保每个问题都有对应的字段
    this.questionList.forEach(itemType => {
      itemType.itemList.forEach(item => {
        this.$set(this.formData, item.itemId, null);
        this.$set(this.answerListData, item.itemId, {});
      });
    });
  },
	data() {
		return {
      questionList,
      scoreLevel,
			formData: {
			},
      answerListData:{},
      postData:{
        recordId:null,
        score:null,
        scoreLevel:null,
        answerList:[]
      },
		}
	},
	methods: {
    // 处理 checkbox 变化事件
    onCheckboxChange(itemType,item) {
      const itemId = item.itemId;
      const selectedValues = this.formData[itemId];
      // 组装post表单提交的数据
      const postItemData = {};
      postItemData.itemTypeId = itemType.itemTypeId;
      postItemData.itemTypeName = itemType.itemTypeName;
      postItemData.itemId = item.itemId;
      postItemData.itemContent = item.itemContent;
      postItemData.optionScore = selectedValues;
      const option = item.optionList.find(opt => opt.value === selectedValues);
      postItemData.optionText = option.text;
      this.answerListData[itemId] = postItemData;
      console.log(this.answerListData);
      // 重新计算总分
      let score = new Decimal(0);
      const values = Object.values(this.formData);
      values.forEach(selectedValues => {
        if(selectedValues !== null){
          score = score.plus(new Decimal(selectedValues));
        }
      });
      this.postData.score = Number(score);
    },
    // 下一步按钮提交
    goProStage() {
      const _that = this;
      //判断是否登录
      if (!isLogin(_that)) {
        return;
      }
      console.log(_that.postData)
      // 判断所有问题是否都已选择了答案
      const values = Object.values(_that.formData);
      // some 方法会遍历数组，只要有一个元素满足条件就返回 true
      const hasUnanswered = values.some(selectedValues => {
        if (selectedValues === null) {
          console.log("还没选择答案呢")
          return true;
        }
        return false;
      });
      if (hasUnanswered) {
        uni.showToast({
          title: '有未选择的题目',
          icon: 'none',
          duration: 1000
        });
        return;
      }
      // 验证是否选择了评价等级
      if(_that.postData.scoreLevel === null){
        uni.showToast({
          title: '请选择评分等级',
          icon: 'none',
          duration: 1000
        });
        return;
      }
      // 请求接口提交基础信息
      _that.postData.answerList = Object.values(_that.answerListData);
      insertScore(_that.postData).then(response => {
        // 显示成功提示
        uni.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 1000,
          complete: function () {
            // 跳转到下一步
            uni.navigateTo({
              url: `/pages/eval/eval_3?recordId=${_that.postData.recordId}&score=${_that.postData.score}`
            })
          }
        });
      });
    },
	}
}
</script>

<style lang="scss">
	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		margin-left: 10px;
	}
	.uni-forms-item {
		margin-bottom: 10px !important;
	}
	.btn_submit {
		padding-bottom: 30px;
	}
  ::v-deep .uni-data-checklist .checklist-group{
    display: block !important;
    padding-top:5px;
  }
  ::v-deep .uni-data-checklist .checklist-group .checklist-box{
    padding:3px;
  }
</style>